function resizeKanban(){
	var bodyWidth = $("body").width();
	var bodyHeight = $(document).height();
	
	if(bodyWidth < 1000){
		$("#wrapper,#header,#box_tasks ul").width(1000);
	}else if(bodyWidth >= 1000){
		$("#wrapper,#header,#box_tasks ul").width("100%");
	}

	var kanbanHeight = bodyHeight - 126;

	if(kanbanHeight < 300){
		$(".box_tasks > ul").height(300);
	}else{		
		$(".box_tasks > ul").height(kanbanHeight);
	}
}

$(window).resize(function() {
	resizeKanban();
});

$(document).ready(function() {
	var idSprint = $.getUrlVar("id");

	resizeKanban();
	loadKanban(idSprint);

	$("#menu_filter").click(function(){
		if($("#toolsbar .filter").css("display") == "none"){
			$("#toolsbar").slideUp('fast',function(){
				$(".tools_left > div",this).hide();
				$(".filter",this).show();

				$('#findBacklog').keyup(function(){
					var valField = new RegExp($(this).val(),"i");
					$("#backlog ul li").each(function(){
						if($(".title",this).text().search(valField) >= 0)
							$(this).css("display","block");
						else
							$(this).css("display","none");
					});
				});

				$(this).slideDown('slow');
			});
		}
	});

	$("#menu_add").click(function(){
		if($("#toolsbar .add").css("display") == "none"){
			$("#toolsbar").slideUp('fast',function(){
				$(".tools_left > div",this).hide();
				$(".add",this).show();

				$(this).slideDown('slow');
			});
		}
	});

	$("#toolsbar .cancel").click(function(){
		$("#toolsbar").slideUp('fast',function(){
			$(".tools_left > div",this).hide();
			$(".title",this).show();

			$(this).slideDown('slow');
		});
	});
});

function showModal(){
	resizeKanban();
}

function closeModal(){
	resizeKanban();
	checkGoingTask();
}


/******************************************************************************************************************
Tasks Functions
******************************************************************************************************************/
function loadKanban(idSprint){
	$.ajax({
		url: SITE+"app/Views/V_Task.php?f=getKanban&idSprint="+idSprint,
		async: false,
		success: function(data){
			var obj = JSON.decode(data);
			
			$(".tools_left").html(obj[1]);
			$("#kanban").html(obj[2]);	
			
			if(obj[0]){
				$("#kanban").data("sprint",obj[3]);				
			}

			resizeKanban();
			
			$.ajax({
				url: SITE+"app/Views/V_Sprint.php?f=getSelectSprints&id="+idSprint,
				async: false,
				success: function(data){
					var obj = JSON.decode(data);

					if(obj[0]){
						$("#kabanSprint").html(' / '+obj[1]);
						$("#actual_sprint").change(function(){
							location = "index.php?id="+$(this).val();
						});
					}
				}
			});			

			$(".box_tasks > ul").each(function(){
				var idTaskState = $(this).attr("id").replace("task_state_","");
				var orderState  = $(this).attr("rel");

				$("li",this).each(function(){
					$(this).children().data("state",idTaskState);
					$(this).children().data("orderState",orderState);
				});
			});

			$(".box_tasks .task").dblclick(function(){
				var id = $(this).attr("id").replace("task_","");
				if(USER_GROUP <= 2){
					editTask(id);
				}else{
					viewTask(id);
				}	
			});
			
			if(USER_GROUP <= 2){
				$(".box_tasks > ul").sortable({
					appendTo: '#kanban',
					containment: '#kanban',
					connectWith: ".box_tasks > ul",
					scroll: true,
					revert: false,
					placeholder: 'placeholder',
					start: function(event, ui) {
						$(".details",$(ui.item)).css("display","none");
						$(".buttons",$(ui.item)).css("display","none");
					},
					update: function(event, ui) {
						//Infos da tarefa
						var idTask				= $(ui.item).children().attr("id").replace("task_","");
						var idTaskState			= $(ui.item).children().data("state");
						var orderTaskState		= $(ui.item).children().data("orderState");
						
						//Infos do Sortable
						var sortIdTaskState		= $(this).attr("id").replace("task_state_","");
						var sortOrderTaskState  = $(this).attr("rel");

						if(sortIdTaskState != idTaskState){
							if(orderTaskState < sortOrderTaskState)
								goingTask(idTask, sortIdTaskState, sortOrderTaskState);
							else
								changeStateTask(idTask, sortIdTaskState, sortOrderTaskState);
						}else{
							changeOrderTask(this);
						}					
					},
					over: function(event, ui) {
						$(this).addClass("active_drop");
					},
					out: function(event, ui) {
						$(this).removeClass("active_drop");
					}
				});
			}

			$(".box_tasks button.expand").click(function(){
				var obj = $(this);
				$(".details",$(this).parent().parent()).slideToggle("fast",function(){
					if($(this).css("display") == "none"){
						obj.html("+");
					}else{
						obj.html("-");
					}
				});
			});

			$(".box_tasks .title_bar").click(function(){
				$("> .buttons",$(this).parent()).slideToggle("fast");
			});

			$(".box_tasks span.status").qtip({
				content: $(this).attr("title"),
				style: {name:'blue', border: {radius:3}, tip:true},
				position: {adjust:{y:0, x:-5}, corner:{target:'leftMiddle',tooltip:'rightMiddle'}}
			});
			
			var flagScrollTop = true;
			$(document).scroll(function(){
				var posToolsbar = $(document).scrollTop();
				
				if(flagScrollTop){
					 $('#toolsbar').animate({top:posToolsbar}, 500, function() {
						$('#toolsbar').animate({top:$(document).scrollTop()}, 100);
						flagScrollTop = true;
					 });
				}

				flagScrollTop = false;
			})
			
		}
	});
}

function loadHTMLTask(obj){	
	var html = "";

	html = obj[1];
	openBox("overlay", html);

	if(obj[0]){
		$("#formTask").validate({
			submitHandler: function(form) {
				var query = $(form).serialize();
				
				$.ajax({
					url: SITE+"app/Views/V_Task.php?f=saveTask&"+query,
					async: false,
					success: function(data){
						var obj = JSON.decode(data);						
						resultMensage(obj, true);
					}
				});

				return false;
			}	
		});

		$(".date-pick").dateinput();
		$("#dateBegin").data("dateinput").change(function() {
			$("#dateLimit").data("dateinput").setMin(this.getValue(), true);
		});
	}else{
		eval(obj[2]);
	}
}


function editTask(id){
	$.ajax({
		url: SITE+"app/Views/V_Task.php?f=editTask&id="+id,
		success: function(data){
			var obj = JSON.decode(data);
			loadHTMLTask(obj);
		}
	});	
}

function viewTask(id){
	$.ajax({
		url: SITE+"app/Views/V_Task.php?f=viewTask&id="+id,
		success: function(data){
			var obj = JSON.decode(data);
			if(obj[0]){
				openBox("overlay", obj[1]);
			}else{
				resultMensage(obj, true);
			}
		}
	});	
}

function deleteTask(id){
	openBox("modalDelete");

	$("#modalDelete #confirm").click(function(){
		$.ajax({
			url: SITE+"app/Views/V_Task.php?f=deleteTask&id="+id,
			success: function(data){
				var obj = JSON.decode(data);
				if(obj[0]){
					$("#task_"+id).remove();
				}			
				resultMensage(obj, true);
			}
		});
	});
}

function attachFile(idTask){
	if(idTask > 0){
		$.ajax({
			url: SITE+"app/Views/V_Task.php?f=addAttach&idTask="+idTask,
			success: function(data){
				var obj = JSON.decode(data);
				if(obj[0]){					
					openBox("overlay", obj[1]);

					$("#uploadify").uploadify({
						'uploader'       : SITE + 'files/swf/uploadify.swf',
						'script'         : SITE + 'files/swf/uploadify.php',
						'cancelImg'      : SITE + 'files/images/icons/cross.png',
						'buttonImg'      : SITE + 'files/images/layout/selecionar_arquivos.gif',
						'width'          : 145,
						'height'         : 24,
						'queueID'        : 'fileQueue',
						'multi'          : true,
						'auto'           : true,
						'onAllComplete'	 : function(event, data) {
							$("#attachFiles button").attr("disabled", false);
						},
						'onInit'		 : function() {
							$("#attachFiles button").attr("disabled", true);
						},
						'onComplete'	 : function(event, queueID, fileObj, reposnse, data) {
							var temp = reposnse;
							if(temp != "0"){								
								$("#uploadSucess span").append(fileObj.name+"<br>");
								
								var countFiles = $('#attachFiles input[name*="files"]').length;
								
								$("<input>").attr({
									type: "hidden",
									name: "files"+countFiles,
									value: temp
								}).appendTo("#attachFiles");
									
								$('#attachFiles input[name="countFiles"]').val(countFiles+1);
							}
						}
					});					

					$("#attachFiles").validate({
						submitHandler: function(form) {
							var query = $(form).serialize();
							
							$.ajax({
								url: SITE+"app/Views/V_Task.php?f=saveAttach&"+query,
								success: function(data){
									var obj = JSON.decode(data);															
									resultMensage(obj, true);
								}
							});
						}
					});
				}
			}
		});	
	}
}

function deleteAttach(id){
	openBox("modalDelete");

	$("#modalDelete #confirm").click(function(){
		$.ajax({
			url: SITE+"app/Views/V_Task.php?f=deleteAttach&id="+id,
			success: function(data){
				var obj = JSON.decode(data);
				if(obj[0]){
					$("#attach_"+id).remove();
				}			
				resultMensage(obj, true);
			}
		});
	});
}

function changeStateTask(idTask, idTaskState, orderTaskState){
	var idSprint = $("#kanban").data("sprint");

	if(idTask > 0 && idTaskState > 0){		
		$.ajax({
			url: SITE+"app/Views/V_Task.php?f=changeStateTask&idTaskState="+idTaskState+"&idTask="+idTask+"&idSprint="+idSprint,
			success: function(data){
				var obj = JSON.decode(data);
				if(obj[0]){
					$("#task_"+idTask).data("state",idTaskState);
					$("#task_"+idTask).data("orderState",orderTaskState);
				}
				
				resultMensage(obj, true);
			}
		});
	}
}

function changeOrderTask(obj){
	var ordersTasks = "";
	var idSprint	= $("#kanban").data("sprint");

	$("li",obj).each(function(){
		if(ordersTasks != "")
			ordersTasks += ",";
	
		if($(this).children().html() != null)
			ordersTasks += $(this).children().attr("id").replace("task_","");
	})
	
	if(ordersTasks != "" && idSprint > 0){
		$.ajax({
			url: SITE+"app/Views/V_Task.php?f=changeOrder&idSprint="+idSprint+"&order="+ordersTasks,
			success: function(data){
			}
		});
	}
}

/******************************************************************************************************************
Andamento das Tarefas Functions
******************************************************************************************************************/
var flagChangeState;
function checkGoingTask(){
	if(flagChangeState){
		flagChangeState = false;
	}else{
		$(".box_tasks > ul").sortable('cancel');
	}
}

function goingTask(idTask, idTaskState, orderTaskState){
	if(idTask > 0){
		$.ajax({
			url: SITE+"app/Views/V_Task.php?f=setGoingTask&idTask="+idTask,
			async: false,
			success: function(data){
				var obj = JSON.decode(data);
				flagChangeState = false; //Se fechar a modal cancela a troca da tarefa.

				if(obj[0]){					
					loadHTMLGoingTask(obj, idTask, idTaskState, orderTaskState);
				}else{
					resultMensage(obj, true);
				}				
			}
		});
	}
}

function loadHTMLGoingTask(obj, idTask, idTaskState, orderTaskState){
	if(obj[0]){
		openBox("overlay", obj[1]);
		
		$("#formGoingTask").validate({
			submitHandler: function(form) {
				var query = $(form).serialize();

				$.ajax({
					url: SITE+"app/Views/V_Task.php?f=saveGoingTask&"+query,
					async: false,
					success: function(data){
						var obj = JSON.decode(data);

						if(obj[0]){					
							flagChangeState = true;
							if(idTaskState != undefined)
								changeStateTask(idTask, idTaskState, orderTaskState);
							else
								resultMensage(obj, true);
						}else{
							resultMensage(obj, true);
						}				
					}
				});
							
				return false;
			}
		});

		$(".date-pick").dateinput();
		$("#viewGoing").click(function(){
			viewTaskGoing(idTask, idTaskState, orderTaskState);
		});
	}else{
		eval(obj[2]);
	}
}

function viewTaskGoing(idTask, idTaskState, orderTaskState){
	$.ajax({
		url: SITE+"app/Views/V_Task.php?f=viewGoingTask&idTask="+idTask,
		async: false,
		success: function(data){
			var obj = JSON.decode(data);
			
			if(obj[0]){					
				openBox("overlay", obj[1]);

				$("#regiterTaskGoing").click(function(){
					goingTask(idTask, idTaskState, orderTaskState);
				});
			}else{
				resultMensage(obj, true);
			}
		}
	});
}

function deleteTaskGoing(id){	
	$.ajax({
		url: SITE+"app/Views/V_Task.php?f=deleteTaskGoing&id="+id,
		success: function(data){
			var obj = JSON.decode(data);
			if(obj[0]){
				$("#taskGoing_"+id).remove();
			}			
			resultMensage(obj, false);
		}
	});
}